<template>
  <div class="login-container">
    <div class="login-content">
      <div class="login-left">
        <div class="system-logo">
          <el-icon class="logo-icon"><Trophy /></el-icon>
          <h1>健身追踪系统</h1>
        </div>
        <div class="system-intro">
          <h3>记录、分析、提升</h3>
          <p>追踪您的健身旅程，实现更健康的生活方式</p>
          <div class="feature-list">
            <div class="feature-item">
              <el-icon><DataLine /></el-icon>
              <span>健康数据记录与分析</span>
            </div>
            <div class="feature-item">
              <el-icon><Timer /></el-icon>
              <span>运动记录与统计</span>
            </div>
            <div class="feature-item">
              <el-icon><Aim /></el-icon>
              <span>健身目标制定与追踪</span>
            </div>
            <div class="feature-item">
              <el-icon><Bell /></el-icon>
              <span>健康提醒与建议</span>
            </div>
          </div>
        </div>
      </div>
      
      <div class="login-right">
        <div class="login-box">
          <div class="login-header">
            <h2>用户登录</h2>
            <p>欢迎回来，请登录您的账号</p>
          </div>       
          <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef">
            <el-form-item prop="username">
              <el-input 
                v-model="loginForm.username" 
                placeholder="请输入用户名" 
                :prefix-icon="User"
              />
            </el-form-item>
            <el-form-item prop="password">
              <el-input 
                v-model="loginForm.password" 
                placeholder="请输入密码" 
                :prefix-icon="Lock"
                type="password" 
                show-password
                @keyup.enter="handleLogin"
              />
            </el-form-item>
            
            <div class="remember-forget">
              <el-checkbox v-model="rememberMe">记住我</el-checkbox>
              <a href="javascript:;" class="forgot-link">忘记密码?</a>
            </div>
            <el-form-item>
              <el-button type="primary" :loading="loading" class="login-button" @click="handleLogin">
                登录
              </el-button>
            </el-form-item>

            <div class="login-options">
              <span>还没有账号?</span>
              <router-link to="/register" class="register-link">立即注册</router-link>
            </div>
          </el-form>
        </div>
      </div>
    </div>
    
    <div class="login-footer">
      <p>© {{ new Date().getFullYear() }} 健身追踪系统 | 提供专业的健身数据分析服务</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Trophy, DataLine, Timer, Aim, Bell } from '@element-plus/icons-vue'
import { login } from '@/api/auth'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const loginFormRef = ref(null)
const rememberMe = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在3到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    // 1. 先进行表单验证，验证未通过则不发送请求
    const valid = await loginFormRef.value.validate()
    if (!valid) {
      return // 验证未通过，直接返回不发送请求
    }
    
    // 清除可能存在的过期token
    userStore.clearLoginInfo()
    
    loading.value = true
    console.log('开始发送登录请求:', loginForm)

    const response = await login(loginForm)
    console.log('登录响应:', response)
    
    // 使用store存储用户信息
    userStore.setLoginInfo({
      token: response.token,
      role: response.role,
      id: response.id,
      username: response.username
    })
    
    // 保存userId到localStorage
    localStorage.setItem('userId', response.id)
    
    // 如果勾选了记住我，可以在此处处理
    if (rememberMe.value) {
      localStorage.setItem('rememberUsername', loginForm.username)
    } else {
      localStorage.removeItem('rememberUsername')
    }
    
    ElMessage.success('登录成功')
    
    // 根据角色重定向到不同的页面
    if (response.role === 'ADMIN') {
      router.push('/exercise-types') // 管理员跳转到运动类型管理页面
    } else {
      router.push('/dashboard') // 普通用户跳转到仪表盘页面
    }
  } catch (error) {
    console.error('登录失败:', error)
    console.log('错误详情:', error.response?.data)
    
    // 根据错误类型提供更具体的错误提示
    let errorMessage = '登录失败，请稍后重试'
    
    if (error.response?.data?.message) {
      // 使用后端返回的错误消息
      errorMessage = error.response.data.message
      
      // 针对特定错误类型进行处理
      if (errorMessage.includes('密码错误')) {
        errorMessage = '密码错误，请重新输入'
      } else if (errorMessage.includes('用户不存在')) {
        errorMessage = '用户名不存在，请检查或注册新账号'
      } else if (errorMessage.includes('账号已被禁用')) {
        errorMessage = '账号已被禁用，请联系管理员'
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElMessage.error(errorMessage)
  } finally {
    loading.value = false
  }
}

// 初始化时检查是否有保存的用户名
const initRememberedUsername = () => {
  const savedUsername = localStorage.getItem('rememberUsername')
  if (savedUsername) {
    loginForm.username = savedUsername
    rememberMe.value = true
  }
}

// 页面加载时执行
initRememberedUsername()
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  display: flex;
  flex-direction: column;
}

.login-content {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px 20px;
}

.login-left {
  display: none;
}

.login-right {
  flex: 1;
  max-width: 420px;
}

.login-box {
  width: 100%;
  padding: 40px;
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  background-color: #fff;
}

.login-header {
  text-align: center;
  margin-bottom: 30px;
}

.login-header h2 {
  margin: 0 0 10px 0;
  color: #303133;
  font-size: 24px;
}

.login-header p {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.remember-forget {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  font-size: 14px;
}

.forgot-link {
  color: #909399;
  text-decoration: none;
}

.forgot-link:hover {
  color: #409EFF;
}

.login-button {
  width: 100%;
  height: 40px;
  font-size: 16px;
}

.login-options {
  margin-top: 24px;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.register-link {
  color: #409EFF;
  text-decoration: none;
  font-weight: 500;
}

.register-link:hover {
  text-decoration: underline;
}

.login-footer {
  text-align: center;
  padding: 20px;
  color: #909399;
  font-size: 12px;
}

/* 响应式设计 */
@media screen and (min-width: 992px) {
  .login-content {
    max-width: 1200px;
    margin: 0 auto;
    gap: 80px;
  }
  
  .login-left {
    display: flex;
    flex-direction: column;
    flex: 1;
    max-width: 500px;
  }
  
  .system-logo {
    display: flex;
    align-items: center;
    gap: 16px;
    margin-bottom: 40px;
  }
  
  .logo-icon {
    font-size: 40px;
    color: #409EFF;
  }
  
  .system-logo h1 {
    margin: 0;
    font-size: 32px;
    color: #303133;
  }
  
  .system-intro {
    color: #606266;
  }
  
  .system-intro h3 {
    font-size: 24px;
    margin-bottom: 16px;
    color: #303133;
  }
  
  .system-intro p {
    font-size: 16px;
    margin-bottom: 32px;
    line-height: 1.6;
  }
  
  .feature-list {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .feature-item {
    display: flex;
    align-items: center;
    gap: 12px;
  }
  
  .feature-item .el-icon {
    font-size: 20px;
    color: #409EFF;
  }
}
</style> 